/**
 * @Author      guang
 * @description store-dict 数字字典
 */
import { reactive, toRefs } from 'vue';
import { defineStore } from 'pinia';
import { postDictDataList } from '@/api/system';
export interface DictState {
  data: any;
  dictEnum: any;
  dictEnumAll: any;
  dictEnumObj: any;
}

export const useStoreDict = defineStore('dict', () => {
  const state = reactive({
    data: {},
    dictEnum: {}, // 存储启用的字典列表
    dictEnumAll: {}, // 存储启用或禁用的字典列表
    dictEnumObj: {}, // 存储启用或禁用的字典对象
  } as DictState);

  const setDictData = (type: any, value: any) => {
    state.data[type] = value;
  };

  // 获取指定dict_type的字典数据
  const updateTargetDict = async (dictType: any, type = 'number') => {
    // 判断缓存数组中是否不存在同类型的dict_type || 相应的缓存数组为空，才去发起请求dict_type请求
    const keys = Object.keys(state.dictEnum);
    if (!keys.includes(dictType) || !state.dictEnum[dictType]?.length) {
      const res = await postDictDataList({
        dictType,
        // itemStatus: 1,
      });
      state.dictEnumAll[dictType] = res.data?.map((item: any) => {
        return {
          ...item,
          label: item.dictLabel,
          value: item.dictValue,
          color: item.itemStyle,
          status: item.itemStatus,
        };
      });
    }
    state.dictEnumAll[dictType] = state.dictEnumAll[dictType].map((item: any) => {
      return {
        ...item,
        value:
          type === 'string'
            ? item.itemCode
            : typeof item.itemCode === 'number'
            ? item.itemCode
            : isNaN(Number(item.itemCode))
            ? item.itemCode
            : Number(item.itemCode),
      };
    });

    state.dictEnumAll[dictType].sort((a: any, b: any) => {
      return a.value - b.value;
    });
    state.dictEnum[dictType] = state.dictEnumAll[dictType]?.filter((item: any) => {
      return item.itemStatus == 1;
    });
    const dictEnumObj: any = {};
    state.dictEnumAll[dictType]?.forEach((item: any) => {
      dictEnumObj[
        type && type === 'string'
          ? item.itemCode
          : typeof item.itemCode === 'number'
          ? item.itemCode
          : isNaN(Number(item.itemCode))
          ? item.itemCode
          : Number(item.itemCode)
      ] = item.itemName;
    });
    state.dictEnumObj[dictType] = dictEnumObj;

    return state.dictEnum[dictType];
  };

  const getEnums = (enumKeys: any) => {
    for (const enumKey of enumKeys) {
      updateTargetDict(enumKey);
    }
  };

  return {
    ...toRefs(state),
    setDictData,
    updateTargetDict,
    getEnums,
  };
});
